import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/user_provider.dart';
import '../models/character.dart';
import '../widgets/gradient_app_bar.dart';
import '../pages/chat_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.index = 0; // 设置默认显示排行榜标签页
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);
    
    // 模拟角色数据，实际应用中应从API或数据库获取
    final List<Character> characters = [
      Character(
        id: '1',
        name: 'Zeus',
        description: 'The king of the gods in Greek mythology, ruler of the sky and thunder',
        imageUrl: 'assets/images/zeus.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Powerful and authoritative, with a sense of justice and wisdom',
        topics: ['Greek Mythology', 'Leadership', 'Power', 'Justice'],
        chatCount: 0,
      ),
      Character(
        id: '2',
        name: 'Athena',
        description: 'Goddess of wisdom and war, Zeus\'s daughter',
        imageUrl: 'assets/images/athena.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Wise and strategic, valuing knowledge and skill',
        topics: ['Wisdom', 'War Strategy', 'Crafts', 'Education'],
        chatCount: 0,
      ),
      Character(
        id: '3',
        name: 'Apollo',
        description: 'God of light, music, prophecy, and medicine',
        imageUrl: 'assets/images/apollo.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Creative and artistic, with a passion for beauty and healing',
        topics: ['Music', 'Art', 'Medicine', 'Prophecy'],
        chatCount: 0,
      ),
      Character(
        id: '4',
        name: 'Aphrodite',
        description: 'Goddess of love and beauty',
        imageUrl: 'assets/images/aphrodite.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Charming and passionate, embodying love and beauty',
        topics: ['Love', 'Beauty', 'Relationships', 'Art'],
        chatCount: 0,
      ),
      Character(
        id: '5',
        name: 'Dr. Smith',
        description: 'Greek mythology researcher, focusing on the study of gods',
        imageUrl: 'assets/images/1.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Scholarly and analytical, with deep knowledge of mythology',
        topics: ['Mythology Research', 'History', 'Archaeology', 'Literature'],
        chatCount: 0,
      ),
      Character(
        id: '6',
        name: 'Johnson',
        description: 'Classical literature professor, studying the Iliad',
        imageUrl: 'assets/images/2.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Academic and insightful, specializing in classical texts',
        topics: ['Classical Literature', 'Poetry', 'Ancient Greek', 'Homer'],
        chatCount: 0,
      ),
      // 新增神话人物
      Character(
        id: '7',
        name: 'Poseidon',
        description: 'God of the sea, earthquakes, and horses',
        imageUrl: 'assets/images/poseidon.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Powerful and temperamental, ruling the oceans with authority',
        topics: ['Oceans', 'Earthquakes', 'Horses', 'Maritime'],
        chatCount: 0,
      ),
      Character(
        id: '8',
        name: 'Hera',
        description: 'Queen of the gods, goddess of marriage and family',
        imageUrl: 'assets/images/hera.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Regal and protective, with a strong sense of justice',
        topics: ['Marriage', 'Family', 'Women', 'Justice'],
        chatCount: 0,
      ),
      Character(
        id: '9',
        name: 'Hermes',
        description: 'Messenger of the gods, god of trade and travelers',
        imageUrl: 'assets/images/hermes.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Quick-witted and resourceful, master of communication',
        topics: ['Communication', 'Trade', 'Travel', 'Trickery'],
        chatCount: 0,
      ),
      Character(
        id: '10',
        name: 'Artemis',
        description: 'Goddess of the hunt, wilderness, and the moon',
        imageUrl: 'assets/images/artemis.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.mythological,
        personality: 'Independent and fierce, protector of nature',
        topics: ['Hunting', 'Wilderness', 'Moon', 'Animals'],
        chatCount: 0,
      ),
      // 新增研究人员
      Character(
        id: '12',
        name: 'Dr. Williams',
        description: 'Archaeologist specializing in ancient Greek artifacts',
        imageUrl: 'assets/images/3.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Detail-oriented and passionate about ancient history',
        topics: ['Archaeology', 'Ancient Artifacts', 'Greek History', 'Excavation'],
        chatCount: 0,
      ),
      Character(
        id: '13',
        name: 'Prof. Brown',
        description: 'Expert in ancient Greek philosophy and ethics',
        imageUrl: 'assets/images/4.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Philosophical and thoughtful, specializing in ancient wisdom',
        topics: ['Philosophy', 'Ethics', 'Ancient Greek', 'Wisdom'],
        chatCount: 0,
      ),
      Character(
        id: '14',
        name: 'Dr. Davis',
        description: 'Linguist studying ancient Greek language and literature',
        imageUrl: 'assets/images/5.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Analytical and precise, with deep knowledge of ancient languages',
        topics: ['Linguistics', 'Ancient Greek', 'Literature', 'Translation'],
        chatCount: 0,
      ),
      Character(
        id: '15',
        name: 'Prof. Wilson',
        description: 'Historian focusing on Greek mythology and religion',
        imageUrl: 'assets/images/6.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Knowledgeable and engaging, expert in religious history',
        topics: ['History', 'Religion', 'Mythology', 'Ancient Greece'],
        chatCount: 0,
      ),
      Character(
        id: '16',
        name: 'Dr. Taylor',
        description: 'Anthropologist studying ancient Greek culture and society',
        imageUrl: 'assets/images/7.png',
        isUnlocked: true,
        requiredCoins: 0,
        type: CharacterType.researcher,
        personality: 'Cultural expert with deep understanding of ancient societies',
        topics: ['Anthropology', 'Culture', 'Society', 'Ancient Greece'],
        chatCount: 0,
      ),
    ];
    
    return Scaffold(
      appBar: GradientAppBar(
        title: 'Characters',
        bottom: TabBar(
          controller: _tabController,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          indicatorColor: Colors.white,
          indicatorWeight: 3,
          dividerColor: Colors.transparent,
          labelStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
          unselectedLabelStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.normal,
          ),
          tabs: const [
            Tab(text: 'Leaderboard'),
            Tab(text: 'Researchers'),
            Tab(text: 'Mythological'),
          ],
        ),
        actions: [
          Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Row(
                children: [
                  const Icon(Icons.monetization_on, color: Colors.amber),
                  const SizedBox(width: 4),
                  Text(
                    '${userProvider.coins}',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildLeaderboard(characters, userProvider),
          _buildCharacterGrid(
            characters.where((c) => c.type == CharacterType.researcher).toList(),
            userProvider,
          ),
          _buildCharacterGrid(
            characters.where((c) => c.type == CharacterType.mythological).toList(),
            userProvider,
          ),
        ],
      ),
    );
  }

  Widget _buildCharacterGrid(List<Character> characters, UserProvider userProvider) {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 16),
            GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 0.80,
                crossAxisSpacing: 16,
                mainAxisSpacing: 16,
              ),
              itemCount: characters.length,
              itemBuilder: (context, index) {
                final character = characters[index];
                return Card(
                  elevation: 4,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => ChatPage(character: character),
                        ),
                      );
                    },
                    borderRadius: BorderRadius.circular(16),
                    child: Stack(
                      children: [
                        // 角色图片
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(16),
                            image: DecorationImage(
                              image: AssetImage(character.imageUrl),
                              fit: BoxFit.cover,
                              onError: (exception, stackTrace) {
                                // 图片加载失败时显示占位图
                              },
                            ),
                          ),
                          child: character.imageUrl.contains('example.com') 
                            ? const Center(
                                child: Icon(
                                  Icons.person,
                                  size: 50,
                                  color: Colors.grey,
                                ),
                              )
                            : null,
                        ),
                        // 渐变遮罩
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(16),
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [
                                Colors.transparent,
                                Colors.black.withOpacity(0.7),
                              ],
                            ),
                          ),
                        ),
                        // 角色名称（左下角）
                        Positioned(
                          left: 12,
                          bottom: 12,
                          child: Text(
                            character.name,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              shadows: [
                                Shadow(
                                  offset: Offset(0, 1),
                                  blurRadius: 3,
                                  color: Colors.black45,
                                ),
                              ],
                            ),
                          ),
                        ),
                        // Info按钮（右上角）
                        Positioned(
                          top: 8,
                          right: 8,
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.black26,
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: IconButton(
                              icon: const Icon(
                                Icons.info_outline,
                                color: Colors.white,
                                size: 20,
                              ),
                              onPressed: () => _showCharacterInfo(context, character),
                              padding: const EdgeInsets.all(4),
                              constraints: const BoxConstraints(
                                minWidth: 32,
                                minHeight: 32,
                              ),
                            ),
                          ),
                        ),
                        // 聊天消耗的货币数量（右下角）
                        Positioned(
                          right: 12,
                          bottom: 12,
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.black45,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const Icon(
                                  Icons.monetization_on,
                                  color: Colors.amber,
                                  size: 16,
                                ),
                                const SizedBox(width: 4),
                                const Text(
                                  '10',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showCharacterInfo(BuildContext context, Character character) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(character.name),
        content: Text(character.description),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }

  Widget _buildLeaderboard(List<Character> characters, UserProvider userProvider) {
    // 按受欢迎程度排序（这里使用 chatCount 作为排序依据）
    final sortedCharacters = List<Character>.from(characters)
      ..sort((a, b) => b.chatCount.compareTo(a.chatCount));
    
    // 只取前10名
    final topCharacters = sortedCharacters.take(10).toList();

    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Top 10 Popular Characters',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            // 前三名特殊布局
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                if (topCharacters.length > 1)
                  _buildTopThreeItem(topCharacters[1], 2),
                if (topCharacters.isNotEmpty)
                  _buildTopThreeItem(topCharacters[0], 1),
                if (topCharacters.length > 2)
                  _buildTopThreeItem(topCharacters[2], 3),
              ],
            ),
            const SizedBox(height: 24),
            // 4-10名列表
            ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: topCharacters.length > 3 ? topCharacters.length - 3 : 0,
              itemBuilder: (context, index) {
                final character = topCharacters[index + 3];
                return _buildLeaderboardListItem(character, index + 4);
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTopThreeItem(Character character, int rank) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ChatPage(character: character),
          ),
        );
      },
      child: Column(
        children: [
          Stack(
            children: [
              CircleAvatar(
                radius: rank == 1 ? 50 : 40,
                backgroundImage: AssetImage(character.imageUrl),
              ),
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: rank == 1 ? Colors.amber : Colors.grey,
                    shape: BoxShape.circle,
                  ),
                  child: Text(
                    rank.toString(),
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            character.name,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),

        ],
      ),
    );
  }

  Widget _buildLeaderboardListItem(Character character, int rank) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: ListTile(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ChatPage(character: character),
            ),
          );
        },
        leading: CircleAvatar(
          backgroundImage: AssetImage(character.imageUrl),
        ),
        title: Text(character.name),
        trailing: Text(
          '#$rank',
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
} 